import java.util.HashSet;
import java.util.Set;

public class Solution996 {
    public int numSquarefulPerms(int[] nums) {
        int[][] f=new int[1<<nums.length][nums.length];
        for (int i=0;i<nums.length;i++){
            f[1<<i][i]=1;
        }
        for (int i=0;i<1<<nums.length;i++){
            for (int j=0;j<nums.length;j++){
                if ((i&(1<<j))==0){
                    continue;
                }
                Set<Integer> set=new HashSet<>();
                for (int k=0;k<nums.length;k++){
                    if (j!=k && (i&(1<<k))!=0 && isSquare(nums[j]+nums[k]) && !set.contains(nums[k])){
                        set.add(nums[k]);
                        f[i][j]+=f[i&(~(1<<j))][k];
                    }
                }
            }
        }
        int ans=0;
        Set<Integer> set=new HashSet<>();
        for (int i=0;i<nums.length;i++){
            if (!set.contains(nums[i])) {
                ans+=f[(1<<nums.length)-1][i];
                set.add(nums[i]);
            }
        }
        return ans;
    }

    private boolean isSquare(int num) {
        int c=(int)Math.sqrt(num);
        return c*c==num;
    }

    public static void main(String[] args) {
        System.out.println(new Solution996().numSquarefulPerms(new int[]{2,2,2}));
    }
}
